import { useCallback, useState } from 'react'
import Taro from '@tarojs/taro'
import i18n from "i18n-js"
import { View, Text } from '@tarojs/components'
import PageContainer from '@/components/PageContainer'
import ListItem from '@/components/ListItem'
import { GButton } from '@/components/GButton'
import { GStyleSheet, DynamicColors } from '@/utils/DarkMode'
import { weekList, WeekDayEnum } from '../utils/tool'
import { updateWeek, getDetail } from '../utils/detailModel'

const SetRepeatScreen = () => {
  const styles = dstyles.useDynamicStyle();
  const [state, setState] = useState<Set<WeekDayEnum>>(new Set(getDetail()!.repeatArray))

  const handleSelect = useCallback((week: WeekDayEnum) => () => {
    if (state.has(week)) {
      state.delete(week)
    } else {
      state.add(week)
    }
    setState(new Set(state))
  }, [state])

  const handleSave = () => {
    updateWeek(state)
    Taro.navigateBack()
  }

  return (
    <PageContainer title={i18n.t('REPEAT')}>
      <View style={styles.container}>
        <View>
          <View style={styles.tip}><Text>{i18n.t('ONCE_TIP')}</Text></View>
          {
            weekList.map(week => {
              const isActive = state.has(week.value)
              return (
                <ListItem
                  key={week.value}
                  onPress={handleSelect(week.value)}
                  extra={
                    <View
                      style={{
                        ...styles.item,
                        borderColor: isActive ? DynamicColors.tintColor.value : '#999',
                        backgroundColor: isActive ? DynamicColors.tintColor.value : 'transparent'
                      }}
                    />}
                >
                  {i18n.t(week.label)}
                </ListItem>
              )
            })
          }
        </View>
        <GButton onPress={handleSave} text={i18n.t('SAVE')} />
      </View>
    </PageContainer>
  )
}

const dstyles = GStyleSheet.create({
  container: {
    width: '100%',
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'space-between',
  },
  tip: {
    padding: 15,
    color: '#333',
    fontSize: 15
  },
  item: {
    width: 15,
    height: 15,
    borderRadius: '50%',
    borderWidth: 1,
    borderStyle: 'solid'
  }
});

export default SetRepeatScreen
